package twitter 
{
	import flash.display.Sprite;
	import flash.events.KeyboardEvent;
	import flash.ui.Keyboard;
	
	/**
	 * @author Nicolas Barradeau
	 * http://en.nicoptere.net
	 */
	public class Manege extends Sprite 
	{
		private var items:Vector.<Class> = Vector.<Class>(	[
															TwitterItem,
															TwitterItem,
															TwitterItem
															] );
		
		private var currentItemId:int = 0;
		private var item:TwitterItem;
		
		public function Manege() 
		{
			
			StaticProperties.stageWidth = stage.stageWidth;
			StaticProperties.stageHeight = stage.stageHeight;
			
			stage.addEventListener( KeyboardEvent.KEY_DOWN, keyboardHandler );
			resetItem();
			
		}
		
		private function onItemOpened(e:TwitterEvent):void 
		{
			item.removeEventListener( TwitterEvent.OPENED, onItemOpened );
			item.start();
		}
		
		private function resetItem( e:TwitterEvent = null ):void 
		{
			if ( item != null )
			{
				if( item.hasEventListener( TwitterEvent.CLOSED ) )item.removeEventListener( TwitterEvent.CLOSED, resetItem );
				removeChild( item );
				item = null;
			}
			
			item = new items[ currentItemId % items.length ]();
			addChild( item );
			item.addEventListener( TwitterEvent.OPENED, onItemOpened );
			item.open();
			
		}
		
		private function keyboardHandler(e:KeyboardEvent):void 
		{
			switch( e.keyCode )
			{
				case Keyboard.LEFT:
					currentItemId--;
					if ( currentItemId < 0 ) currentItemId = items.length - 1;
					item.addEventListener( TwitterEvent.CLOSED, resetItem );
					item.close();
				break;
				
				case Keyboard.RIGHT:
					currentItemId++;
					item.addEventListener( TwitterEvent.CLOSED, resetItem );
					item.close();
				break;
			}
			
		}
		
	}

}